package com.study.base;

/**
 * @description: DeadLockTest  手写一个死锁
 * @date: 2020/11/12 15:34
 * @author: hcm
 * @version: 1.0
 */
public class DeadLockTest implements Runnable{

    public static void main(String[] args) {
        DeadLockTest d1 = new DeadLockTest();
        DeadLockTest d2 = new DeadLockTest();
        new Thread(d1).start();
        new Thread(d2).start();
    }

    //1.锁的目的是锁住共享资源，所以我们要有两个共享对象模拟锁的相互持有
    private  static  Object o1 = new Object(),o2 = new Object();

    //死锁状态
    Boolean statusFlag;
    //进入多线程模式
    @Override
    public void run() {
        //锁对象头
        synchronized (o1){
            statusFlag = true;
            //休眠
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //这里的o2被对象一锁定
            synchronized (o2){
                System.out.println("对象一锁定");
            }
        }
        synchronized (o2){
            System.out.println("获取资源中。。。。");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //形成
            synchronized (o1){
                statusFlag = false;
                System.out.println("对象二锁o1");
            }
        }
    }
}
